<template>
  <div>
    <div style="display:flex;">
      <el-upload
        :http-request="handlerUpload"
        style="margin-right: 12px"
        action=""
        :limit="1"
        :on-exceed="handlExceed"
        :show-file-list="false">
        <el-button type="success" size="medium" round
                   style="color: #fff;background-color: #00ca90;border-color: #00ca90;"
                   v-if="$store.getters.userInfo.usertype === 0">
          上传文件
        </el-button>
      </el-upload>

      <el-button type="success" size="medium" round
                 style="color: #fff;background-color: #00ca90;border-color: #00ca90;"
                 @click.native="resource.ioFormVisible = true"
                 v-if="$store.getters.userInfo.usertype === 0">
        创建目录
      </el-button>
      <el-button type="success" size="medium" round
                 style="color: #fff;background-color: #00ca90;border-color: #00ca90;" @click="stepBack">
        返回上级
      </el-button>
    </div>
    <div style="text-align: left" :key="resource.key">
      <div style="margin: 20px 0;font-size: 15px;text-indent: 15px">当前目录:{{ resource.currentDir }}</div>
      <p v-if="resourceList.length === 0" style="text-align: center">暂无文件</p>
      <div>
        <ul>
          <li v-for="io  in resourceList" style="padding: 10px 10px">
            <div slot="reference" @click = "io.fileName?download(io.fileName):stepDir(io.dirName)">
              <el-tooltip :content="io.fileName?io.fileName:io.dirName" placement="bottom" effect="light">
                <FileCard :file-name="io.fileName" v-if="io.fileName"></FileCard>
                <DirectoryCard :dir-name="io.dirName" v-if="io.dirName"></DirectoryCard>
              </el-tooltip>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <el-dialog title="创建目录" :visible.sync="resource.ioFormVisible">
      <div style="display: flex;">
        <el-input v-model="resource.ioName" placeholder="输入目录名称"/>
        <el-button style="margin-left: 20px" type="primary" @click="createDir">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import FileCard from "./FileCard";
import DirectoryCard from "./DirectoryCard";
import {Auth} from "../store/user/auth";
import {mymessage} from "../tools/mymessage";
import {service} from "../tools/api";
import {downFileFromBlob} from "../tools/download";
import axios from "axios";

export default {
  name: "ResourceBoard",
  components: {DirectoryCard, FileCard},
  props: {
    courseCode: String
  },
  data() {
    return {
      visible: false,
      resource: {
        key: 1,
        currentDir: '/',
        dirStack: [],
        ioFormVisible: false,
        ioName: "",
      },
      resourceList: []
    }
  },
  created() {
    this.init();
  },
  mounted() {
    console.log(this.courseCode)
  },
  methods: {
    init() {
      this.resourceList = [];
      this.resource.currentDir = this.convertStackToDir();
      this.getDirList(this.resource.currentDir);
      this.getFileList(this.resource.currentDir);
    },
    sortResourceList() {
      this.resourceList.sort((a, b) => {
        if (a.dirName && b.fileName) {
          return -1;
        } else if (a.fileName && b.dirName) {
          return 1;
        } else {
          return 0;
        }
      });
    },
    convertStackToDir() {
      let path = "/";
      this.resource.dirStack.forEach(dir => {
        path += dir + '/';
      });
      return path;
    },
    keyChange() {
      this.resource.key++;
    },
    stepBack() {
      if (this.resource.currentDir === '/') {
        mymessage.info("当前已为根目录");
      } else {
        this.resource.dirStack.pop();
        this.init();
      }
    },
    stepDir(dirName) {
      this.resource.dirStack.push(dirName);
      this.init();
    },

    uploadFile(file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("userName", this.courseCode);
      formData.append("dirName", this.resource.currentDir);

      this.uploadService(formData).then(res => {
        console.log(res);
        if (res.data.code === 200) {
          mymessage.success(res.data.msgStr);
          this.init();
        } else {
          mymessage.error(res.data.msgStr);
        }
      }).catch(err => {
        console.log(err);
      });
    },

    uploadService(data) {
      return service.post(
        '/file/upload',
        data,
      );
    },

    download(fileName) {
      let path = this.resource.currentDir + fileName;
      this.downloadService(path).then(res => {
        if (res.status === 200) {
          console.log(res)
          downFileFromBlob(res.data, fileName);
        }
      }).catch(err => {
        console.log(err);
      })
    },

    downloadService(fileName) {
      return service.get(
        '/file/download',
        {
          params: {
            userName: this.courseCode,
            fileName: fileName
          },
          responseType: "blob"
        }
      );
    },

    handlerUpload(fileObj) {
      this.uploadFile(fileObj.file);
    },
    handlExceed(fileList) {
      this.uploadFile(fileList[0]);
    },

    creatDirService(dirName, parentDirName) {
      return service.post(
        '/file/createDirectory',
        {},
        {
          params: {
            userName: this.courseCode,
            dirName: dirName,
            parentDirName: parentDirName
          }
        }
      );
    },

    fileListService(dirName) {
      return service.get(
        '/file/getFileList',
        {
          params: {
            userName: this.courseCode,
            dirName: dirName
          }
        }
      );
    },

    dirListService(dirName) {
      return service.get(
        '/file/getDirList',
        {
          params: {
            userName: this.courseCode,
            dirName: dirName
          }
        }
      );
    },

    getFileList(dirName) {
      console.log(dirName)
      console.log(this.courseCode)
      this.fileListService(dirName).then(res => {
        console.log(res);
        if (res.data.code === 200) {
          this.resourceList.push(...res.data.data);
          this.sortResourceList();
          this.keyChange();
        }
      }).catch(err => {
        console.log(err);
      });
    },

    getDirList(dirName) {
      this.dirListService(dirName).then(res => {
        console.log(res)
        if (res.data.code === 200) {
          this.resourceList.push(...res.data.data);
          this.sortResourceList();
          this.keyChange();
        }
      }).catch(err => {
        console.log(err)
      });
    },

    createDir() {
      let parentDirName = this.resource.currentDir;
      let dirName = this.resource.ioName;

      this.creatDirService(dirName, parentDirName).then(res => {
        if (res.data.code === 200) {
          mymessage.success(res.data.msgStr);
          this.init();
        } else {
          mymessage.error(res.data.msgStr);
        }
        this.resource.ioName = "";
        this.resource.ioFormVisible = false;
      }).catch(err => {
        console.log(err);
      });
    },

    deleteFileService(userName, dirName, fileName) {
      return axios.post(
        '/file/deleteFile',
        {},
        {
          params: {
            userName: userName,
            dirPath: dirName,
            fileName: fileName
          }
        }
      );
    },

    deleteFile(fileName) {
      this.deleteFileService(this.courseCode, this.resource.currentDir, fileName).then(res => {
        if (res.data.code === 200) {
          mymessage.success("删除成功");
          this.init();
          this.keyChange();
        } else {
          mymessage.error(res.data.msgStr);
        }
      }).catch(err => {

      });
    },

    deleteDirService(userName, dirName) {
      return axios.post(
        '/file/deleteDir',
        {}, {
          params: {
            userName: userName,
            dirName: dirName
          }
        }
      )
    },

    deleteDir(dirName) {
      this.deleteDirService(this.courseCode, this.resource.currentDir+dirName).then(res => {
        if (res.data.code === 200) {
          mymessage.success("删除成功");
          this.init();
          this.keyChange();
        } else {
          mymessage.error(res.data.msgStr);
        }
      }).catch(err => {
        console.log(err);
      })
    }
  },


}
</script>

<style scoped>
li:hover {
  cursor: pointer;
}

</style>
